<template>
    <div>
         <el-drawer
            :title="title+'物料'"
            :visible.sync="drawer"
            :before-close="handleClose"
            custom-class="demo-drawer"
            ref="drawer"
             size="90%">
              <div class="demo-drawer__content">
                    <div class="demo-drawer__content_from">
                        <div class="from">
                            <el-scrollbar wrap-class="scrollbar-wrapper "  ref="resetScroll"   >
                                <el-form :model="userForm" :rules="rules" ref="userForm"  label-width="120px" >
                                    <el-tabs   :value="tabs" class="tablist" @tab-click="tabClick">
                                        <el-tab-pane :disabled="(title=='修改' && tabs!=String(i)) "  v-for="(item,i) in formdata " :key="item.name_bt"  :label="item.name_bt" :name="String(i)">
                                            <span slot="label"><i :class="item.ico"></i> {{item.name_bt}}</span>
                                                   <el-form-item label="物料名称：" prop="name">
                                                        <el-input v-model="userForm.name"></el-input>
                                                    </el-form-item>
                                                <div v-if="tabs=='0'" class="tabsbox">
                                                    <el-form-item label="上传图片：">
                                                        <el-upload
                                                            class="upload-demo"
                                                            action
                                                            ref="upload"
                                                            drag
                                                            :auto-upload="true"
                                                            accept=".png,.jpg,.jpeg,.gif"
                                                            :on-change="handleChange"
                                                            :show-file-list="false"
                                                            :before-upload="beforeupload"
                                                            multiple>
                                                            <i class="el-icon-upload"></i>
                                                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                                            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
                                                        </el-upload>
                                                    </el-form-item>
                                                    <el-form-item label="图片宽(px)：">
                                                        <el-input v-model="userForm.i_width" :disabled="true"></el-input>
                                                    </el-form-item>
                                                    <el-form-item label="图片高(px)：">
                                                        <el-input v-model="userForm.i_height" :disabled="true"></el-input>
                                                    </el-form-item>
                                                    <el-form-item label="描述：">
                                                        <el-input v-model="userForm.description"></el-input>
                                                    </el-form-item>
                                                    <el-form-item label="点击链接：" prop="i_click_url">
                                                        <el-input v-model="userForm.i_click_url"></el-input>
                                                    </el-form-item>
                                                    <el-form-item label="目标窗口：">
                                                            <el-radio v-model="userForm.target_window" label="0">新窗口</el-radio>
                                                            <el-radio v-model="userForm.target_window" label="1">原窗口</el-radio>
                                                    </el-form-item>
                                                    <div class="flexd_img" :v-if="userForm.i_url"  >
                                                        <el-image class="avatar" v-if="!fileimg" :src="urllink + userForm.i_url" fit="scale-down">
                                                            <div slot="error" class="image-slot"></div>
                                                        </el-image>  
                                                          <el-image class="avatar" v-else :src="userForm.i_url" fit="scale-down">
                                                            <div slot="error" class="image-slot"></div>
                                                        </el-image>  
                                                    </div>
                                                    
                                                </div>
                                                <div v-if="tabs=='1'">
                                                    <div class="p_line_tishi">
                                                        自定义模版输入代码时,如果是新增点击统计链接用{c}0{/c},新增上传图片src用{i}0{/i},新增flash文件src用{f}0{/f},
                                                        后台会自动替换成对应的上传文件的地址,代码尽量用双引号,少换行,加结束;防止解析出错,更换素材时请先删除素材,然后重新上传素材
                                                    </div>
                                                    <el-form-item label="模版类型：">
                                                        <el-radio-group  v-model="templates_id" size="medium">
                                                                <el-radio  :label='false'>不使用模板</el-radio>
                                                                <el-radio  :label='true'>使用系统模版</el-radio>
                                                        </el-radio-group>
                                                    </el-form-item>
                                                    <el-form-item label="代码：" v-show="!templates_id">
                                                           <el-input type="textarea" v-model="userForm.body" size="medium " :autosize="{ minRows: 2, maxRows: 19}"  class="el-textarea_wrap" ></el-input>
                                                    </el-form-item>
                                                    <el-form-item label="系统模板：" v-show="templates_id">
                                                         <el-select v-model="userForm.templates_id" filterable placeholder="请选择">
                                                            <el-option
                                                                v-for="item in select_codebits" 
                                                                :key="item.name"  
                                                                :label="item.name" 
                                                                :value="item.id">
                                                            </el-option>
                                                        </el-select>
                                                    </el-form-item>
                                                    <div class="p_line_tishi">
                                                           c表示点击链接数,i表示图片上传数,f表示flash上传数
                                                    </div>
                                                    <el-form-item label="点击链接：">
                                                        <div slot="label">
                                                            <span>点击链接：</span>
                                                            <el-tooltip placement="bottom-start" popper-class="popperClass">
                                                            <div slot="content">
                                                                输入需要统计点击量的url地址,后台会统计该url的点击量
                                                            </div>
                                                            <div class="ico">?</div>
                                                        </el-tooltip>
                                                        </div>
                                                        <div class="ul_">
                                                            <div class="li_" v-for="(valname ,i) in userForm.click_urls" :key="i">
                                                                <el-input v-model="userForm.click_urls[i]"></el-input>
                                                                <el-button size="mini" @click="urlarrClick(i)" :icon="i==0?'el-icon-edit':'el-icon-delete' " :type="i==0?'primary':'danger'">{{ i==0? '新增' :'删除'}}</el-button>
                                                            </div>
                                                        </div>
                                                     </el-form-item>
                                                    <el-form-item >
                                                        <div slot="label">
                                                            <span>上传图片：</span>
                                                            <el-tooltip placement="bottom-start" popper-class="popperClass">
                                                                <div slot="content">
                                                                    文件需小于256KB<br>建议使用大小较小的文件，因为文件越大，网页的加载时间就越长，将影响您的网站的用户体验。
                                                                </div>
                                                                <div class="ico">?</div>
                                                            </el-tooltip>
                                                        </div>
                                                        <el-upload
                                                            action
                                                            list-type="picture-card"
                                                            ref="upload"
                                                            :limit=5
                                                            :auto-upload="true"
                                                            :file-list="fileList"
                                                            accept=".png,.jpg,.jpeg,.gif"
                                                            :on-preview="handlePictureCardPreview"
                                                            :on-remove="removefilelist"
                                                            :before-upload="beforeupload"
                                                            :http-request="handleUpload"
                                                             >
                                                            <i slot="default" class="el-icon-plus"></i>
                                                        </el-upload>
                                                    </el-form-item>
                                                </div>
                                        </el-tab-pane>
                                    </el-tabs>
                                </el-form>
                            </el-scrollbar>
                        </div>
                        <div class="demo-drawer__footer">
                            <el-button type="primary"  @click="submitForm('userForm')" :loading="loading">{{ loading ? '提交中 ...' : title=="新建"? '新 建' :'修 改' }}</el-button>
                            <el-button @click="handleClose">取 消</el-button>
                        </div>
                    </div>
                </div>
         </el-drawer>
         <el-dialog :visible.sync="dialogVisible" width="40%" top='5vh' :title="dialogImagename">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
    </div>
</template>
<script>
import { axios_adversense,axios_uploadimg,axios_matter_update} from "@/api/infor";
export default {
    name:'material_from',
    data(){
        return{
            loading:false,
            rules:{
                name: [
                    { required: true, message: '请输入物料名称', trigger: 'blur' }
                ] ,
                i_click_url: [
                    { required: true, message: '请输入点击链接', trigger: 'blur' }
                ] ,
            },
            dialogVisible: false,  //图片查看器
            dialogImageUrl: '',
            dialogImagename:'',
            tabs:'0',
            fileimg:false,
            fileList:[],
            fileListfor:[],
            urllink:process.env.VUE_APP_API_BASE_URLLINK,
            templates_id:false,
            userForm:{
                matter_type:'',  //	类型 	1添加 2修改 3删除
                id:'',           //	修改删除id   
                name:'',         //	名称
                mateer_mode:'',  //	1图片 2富媒体
                 i_url:'',        //	图片素材地址
                i_width:'',      //	图片素材宽度
                i_height:'',     //	图片素材高度
                description:'',  //	图片描述
                i_click_url:'',  //	图片点击链接地址
                target_window:"1", //目标窗口 	0新窗口1原窗口

                templates_id:'',  //模板编号
                body:'',          //html代码
                click_urls:[''],    //点击链接列表
                m_urls:[ ],        //素材图片列表
                f_urls:'',        //flash地址
            },
            select_codebits_val:'全部',
            select_codebits:[{name:"全部",id:'0'}],
            formdata:[
                {
                    name_bt:'图片',ico:'el-icon-picture',
                },
                {
                    name_bt:'富媒体',ico:'el-icon-video-camera-solid',
                }
            ],
        }
    },
    props:{
        drawer:{
            type: Boolean,
            default:false,
        },
        item:{
        },
        title:{},
    },
    computed:{
       datawatch(){
        let title=this.title
        let item=this.item;
         let drawer=this.drawer;
        return {title,item,drawer}
       },
       file_List(){
         let item=[{name:'',url:''}]
        this.userForm.m_urls.forEach((item_)=>{
            item.push({name:item_,url:item_})
        })
          return item
       },
       body(){
        return this.$htmlUnescape( this.userForm.body);
       }
    },
    watch:{
        datawatch:{
            immediate:true,
            handler(n){
                 if(n.drawer){
                    Object.assign(this.$data,this.$options.data.call(this));
                     if( n.item!=''){
                        this.tabs=n.item.type=="图片"? '0' :'1',
                         this.userForm.id=n.item.id;
                         this.userForm.name=n.item.name;
                        //   if(n.item.type=='图片'){
                          if(n.item.img){
                            this.userForm.i_url=n.item.img.i_url;
                            this.userForm.i_width=n.item.img.i_width;
                            this.userForm.i_height=n.item.img.i_height;
                            this.userForm.description=n.item.img.description;
                            this.userForm.i_click_url=n.item.img.i_click_url;
                            this.userForm.target_window=n.item.img.target_window;
                          }
                        if(n.item.media){
                            // this.userForm.body=n.item.media.body;
                            this.userForm.body=this.$htmlUnescape( n.item.media.body);
                            this.userForm.click_urls=n.item.media.click_urls;
                            this.userForm.m_urls=n.item.media.m_urls;
                            let itema=[];
                            this.userForm.m_urls.forEach((item_)=>{
                                    itema.push({name:item_,url:item_})
                                })
                            this.fileList=itema;
                            this.userForm.f_urls=n.item.media.f_urls;
                             this.userForm.templates_id=parseInt(n.item.media.templates_id) ;
                            this.templates_id= this.userForm.templates_id=='0'? false : true;
                         }
                    }else{
                        this.$nextTick(()=>{
                            this.$refs.resetScroll.wrap.scrollTop=0;
                            this.$refs["userForm"].clearValidate();
                        })
                    }
                } 
            }
        },
    },
    created(){
        this.axiosAdversense() //代码组
    },

    methods:{
        //   添加图片
        handleChange(file) {
            this.fileimg=file;
            this.userForm.i_url = URL.createObjectURL(file.raw);
            let img=new Image();
            img.src= this.userForm.i_url;
            let that=this;
            img.onload=function(){
                that.$nextTick(()=>{
                    that.userForm.i_width=img.width;
                    that.userForm.i_height=img.height;
                })
            }
        },
        // 点击多选
          // 上传前调用
        beforeupload(file){
            let isLt5M = file.size / 1024 / 1024 < 50;
            let isJPG =file.type === "image/jpeg" || file.type === "image/png";
            if (!isJPG) {this.$message.error("上传头像图片只能是 JPG 、png 格式!");return false;}
            if(!isLt5M){this.$message.error("上传头像图片大小不能超过 50MB!");return false;}
        },
        //   打开图片的查看
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogImagename = file.name;
            this.dialogVisible = true;
        },
        // 自定义上传
        handleUpload( file){
           var fromDate=new FormData();  
             fromDate.append("files[0]",file.file);
            axios_uploadimg( fromDate ).then((res) => {
                if(res.data.code==1){
                   this.userForm.m_urls= this.userForm.m_urls.concat(res.data.uploadedFiles[0].filePath);
                }
            }).catch(( )=>{})
        },
        // handleUploadone(file){
        //      var fromDate=new FormData();  
        //      fromDate.append("files[0]",file.file);
        //     axios_uploadimg( fromDate ).then((res) => {
        //         if(res.data.code==1){
        //            this.userForm.img.i_url= res.data.uploadedFiles[0].filePath;
        //            this.userForm.img.i_width= res.data.uploadedFiles[0].width;
        //            this.userForm.img.i_height= res.data.uploadedFiles[0].height;
        //         }
        //     }).catch(( )=>{})
        // },
        removefilelist(file){
             this.userForm.m_urls.forEach((item_,index)=>{
                if(item_==file.name){
                     this.userForm.m_urls.splice( index,1);
                }
            })
        },
       
        tabClick(e){
            this.tabs=e.index;
        },
        urlarrClick(index){
            if(index==0){
                if( this.userForm.click_urls.length>=5){
                    this.$message.error('最多添加5条链接哦！');
                    return false;
                }
                this.userForm.click_urls.push('');
            }else{
                this.userForm.click_urls.splice(index,1);
            }
        },
        handleClose(){
        //     this.$confirm('取消编辑将不保留已经填写的数据，确定继续吗？','取消编辑',{customClass:'layeralterelbox'}) .then(()  => {
        //    }).catch(()  => {});
            this.$emit("handleClose",this.drawer)
        },
          // 提交个人信息
          submitForm(formName){
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if(this.fileimg){  //上传了图片后提交的数据
                         var fromDate=new FormData();  
                         fromDate.append("files[0]",this.fileimg.raw);
                         fromDate.append("i_width",this.userForm.i_width);
                         fromDate.append("i_height",this.userForm.i_height);
                        axios_uploadimg( fromDate  ).then((res) => {
                            if(res.data.code==1){
                               this.userForm.i_url= res.data.uploadedFiles[0].filePath;
                               this.userForm.i_width= res.data.uploadedFiles[0].width;
                               this.userForm.i_height= res.data.uploadedFiles[0].height;
                              this.submit_form()
                            }
                        }).catch(( )=>{})
                    } else{
                        this.submit_form()   //未上传图片后提交的数据
                    }
                } else {
                    return false;
                }
            });
        },
        submit_form(){
            if(this.title=="修改"){
                this.userForm.matter_type=2;
            }else{
                this.userForm.matter_type=1;
            }
                let form={
                matter_type:this.userForm.matter_type,  
                id:this.userForm.id,  
                name:this.userForm.name,  
                mateer_mode:'2', 
            }
            if(this.tabs=='0'){
                form.i_url=this.userForm.i_url;
                form.i_width=this.userForm.i_width; 
                form.i_height=this.userForm.i_height; 
                form.description=this.userForm.description; 
                form.i_click_url=this.userForm.i_click_url; 
                form.target_window=this.userForm.target_window;
                form.mateer_mode='1'
            }
            if(this.tabs=='1'){
                if(!this.templates_id){
                    form.templates_id='0';
                    form.body=this.userForm.body; 
                }else{
                     form.templates_id=this.userForm.templates_id;
                }
                form.click_urls=this.userForm.click_urls; 
                form.m_urls=this.userForm.m_urls; 
                form.f_urls=this.userForm.f_urls; 
                form.mateer_mode='3'
            }
            axios_matter_update(form).then((res) => {
                if(res.data.code==1){
                    this.loading=false;
                    this.$emit("handleClose",this.drawer)
                    this.$emit("matterUpdate",true)
                }
            }).catch(( )=>{})
        },
        // 获取代码位的分类
        axiosAdversense(){
           axios_adversense({model:5,flow_type:'0'}).then((res) => {
                 this.select_codebits.push(res.data.data);
                 this.select_codebits=this.select_codebits.flat(Infinity)
            }).catch(( )=>{})
        },
    }
}
</script>
<style lang="scss"   >
  .tablist.el-tabs {
    .el-tabs__header{
        margin-bottom: 30px;
    }
    .el-tabs__content{
        background: #fff;
        width: auto;
        max-width: 960px;
         .el-textarea_wrap .el-textarea__inner{
            min-width: 600px !important;
        }
    }
    .el-tabs__item{
        font-size: 16px;
       
     }
     .el-form-item{
      padding-bottom: 0px;
  }
     .tabsbox{
        position: relative;
     }
     .flexd_img{
        position: fixed;
        border:1px solid #ddd;
        width: 450px;
        height: 450px;
        bottom: 150px;
        right: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        background: #fff;
        .avatar{
            max-width: 90%;
            max-height: 90%;
        }
     }
     
     .el-form-item__content{
      .el-input{
          max-width: 400px !important;
          min-width: 300px !important;
      }
  }
  }
</style>
<style scoped>
  .from .ico{
    margin:1px 0px 2px 0px !important;
  }
</style>